package com.baicai.baicaiknowledgeai.controller;

import com.baicai.baicaiknowledgeai.entity.User;
import com.baicai.baicaiknowledgeai.service.IUserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 用户功能控制器
 * @author 白菜
 */
@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 获取当前登录的用户信息
     */
    @GetMapping("/api/user/me")
    @ResponseBody
    public ResponseEntity<User> getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            // 为了安全，返回前清除密码
            user.setPassword(null);
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    /**
     * 处理用户登录请求
     */
    @PostMapping("/login")
    public String handleLogin(@RequestParam String username,
                              @RequestParam String password,
                              HttpSession session,
                              RedirectAttributes redirectAttributes) {
        User user = userService.login(username, password);
        if (user != null) {
            // 登录成功，将用户信息存入 session
            session.setAttribute("user", user);
            return "redirect:/chat";
        } else {
            // 登录失败，重定向回登录页并给出提示
            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
            return "redirect:/login";
        }
    }

    /**
     * 处理用户登出请求
     */
    @PostMapping("/logout")
    public String handleLogout(HttpSession session) {
        // 销毁 session
        session.invalidate();
        return "redirect:/login";
    }
}